package multiThreading;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 第三种：通过Callable接口方式实现多线程
 * Created by lomo .
 */
public class MultiThreadsByCall implements Callable<Integer>{

    private static int N = 10;

    MultiThreadsByCall() {

    }

    // main函数会启动main线程.
    public static void main(String[] args) {
        MultiThreadsByCall multiThreadsByCall = new MultiThreadsByCall();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(multiThreadsByCall);
//        new Thread(futureTask).start();

        for (int i = 0; i < MultiThreadsByCall.N; i ++) {
            System.out.println("线程 "+ Thread.currentThread().getName() + " 的当前循环变量值为：" + i);
            if (i == 5) {
                new Thread(futureTask, "有返回值的线程").start();
            }
        }

        try {
            System.out.println("子线程的返回值: " + futureTask.get());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer call() throws Exception {
        int i;
        for (i = 0; i < this.N; i ++) {
            System.out.println("线程: " + Thread.currentThread().getName() + " 调用了 " + i);
        }
        return i;
    }
}
